package com.canbot.u05.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.canbot.u05.MainApplication;
import com.canbot.u05.R;
import com.canbot.u05.api.ReceiveData;
import com.canbot.u05.control.RobotMgr;
import com.canbot.u05.utils.Config;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.utils.WifiUtils;

import java.util.List;

/**
 * 开机动画页面。
 * 如果没有连接机器人的热点，或者连接了热点但是不能成功连接192.168.12.12SOCKET，
 * 则一直停留在此页面.
 */
public class Splash extends Activity {

        private final static String TAG = "Splash";

        protected static final int PLAY_ANIM = 0;

        // 搜索附近 wifi
        public static final int SCAN_WIFI = 1;

        // 连接到 U05- wifi
        public static final int CONNECTED_U05 = 2;

        private TextView mTv;

        private Dialog tipDialog;

        private Handler mHandler = new Handler() {
                @Override
                @SuppressWarnings("unchecked")
                public void handleMessage(Message msg) {
                        switch (msg.what) {
                                case PLAY_ANIM:
                                        String num = "u5_bootanimation" + index;
                                        BitmapDrawable bitmapDrawable = new BitmapDrawable(
                                                BitmapFactory.decodeStream(getResources()
                                                        .openRawResource(getResources()
                                                                .getIdentifier(num, "drawable",
                                                                        "com.canbot.u05"))));
                                        logoView.setBackground(bitmapDrawable);

                                        index++;

                                        if (index > 41) {
                                                index = 0;
                                        }
                                        mHandler.sendEmptyMessageDelayed(PLAY_ANIM, 118);
                                        break;
                                case SCAN_WIFI:
                                        mWifiUtils.startScan();
                                        List<ScanResult> wifiList = mWifiUtils.getWifiList();
                                        if (wifiList != null && wifiList.size() > 0) {
                                                for (ScanResult result : wifiList) {
                                                        if (WifiUtils.isU05Wifi(result.SSID)) {
                                                                Logger.e(TAG, "ssid = " + result.SSID);
                                                                mWifiUtils.connect(result.SSID, Config.ROBOT_WIFI_PASSWORD);
                                                                return;
                                                        }
                                                }
                                        }
                                        mHandler.sendEmptyMessageDelayed(SCAN_WIFI, 60 * 1000);
                                        break;
                                case CONNECTED_U05:
                                        Logger.e(TAG, "CONNECTED " + Config.ROBOT_WIFI_NAME_PREFiX);
                                        mHandler.removeMessages(SCAN_WIFI);
                                        if (RobotMgr.getInstance().connectToServer()) {
                                                new ReceiveData(Splash.this);
                                                gotoNextActivity();
                                        }
                                        else {
											    ToastTools.newInstance(Splash.this).showText(getString(R.string.failed_connect_robot_socket));
                                                mHandler.sendEmptyMessageDelayed(CONNECTED_U05, 1 * 1000);
										}
                                      
                                        break;
                                default:
                                        break;
                        }
                }
        };

        private ImageView logoView = null;

        private WifiUtils mWifiUtils;

        private WifiReceiver mWifiReceiver;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                requestWindowFeature(Window.FEATURE_NO_TITLE);
                getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                        WindowManager.LayoutParams.FLAG_FULLSCREEN);
                getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                        WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

                setContentView(R.layout.splash);
                logoView = (ImageView) findViewById(R.id.image_logo);
                logoView.setBackgroundResource(R.drawable.u5_bootanimation0);

                connectU05Wifi();

        }

        /**
         * 连接 U05- wifi
         */
        public void connectU05Wifi() {
                mWifiUtils = WifiUtils.getInstance();
                String ssid = mWifiUtils.getSSID();
                if (WifiUtils.isU05Wifi(ssid)) {
                        mHandler.sendEmptyMessage(CONNECTED_U05);
                }
                else {
						ToastTools.newInstance(Splash.this).showText(getString(R.string.not_connected_robot_hotspot));
                        registerWifiReceiver();
                        mHandler.sendEmptyMessage(SCAN_WIFI);
                }
        }


        private int index = 0;

        @Override
        protected void onResume() {
                super.onResume();
                cancelDialog();
                startAnim();
                Logger.d(TAG, "onresume");
        }

        @Override
        protected void onPause() {
                super.onPause();
                stopAnim();
                Logger.d(TAG, "onPause");
                mHandler.removeMessages(PLAY_ANIM);
        }

        @Override
        protected void onDestroy() {
                super.onDestroy();
                unRegisterWifiReceiver();
        }

        private void startAnim() {
                Logger.i(TAG, "startAnim");
                index = 0;
                mHandler.sendEmptyMessage(PLAY_ANIM);
        }

        private void stopAnim() {
                Logger.i(TAG, "stopAnim");
        }


        private void gotoNextActivity() {
                Logger.e(TAG, "gotoNextActivity MyRobotActivity");
                Intent i = new Intent();
                i.setClass(this, MyRobotActivity.class);
                startActivity(i);
                finish();
        }


        /**
         * 取消提示的tipDialog
         */
        private void cancelDialog() {
                if (tipDialog != null) {
                        if (tipDialog.isShowing()) {
                                tipDialog.cancel();
                                Log.e(TAG, "dialog is canceled");
                        }
                        tipDialog = null;
                }
        }


        @Override
        public void onBackPressed() {

        }

        @Override
        protected void onNewIntent(Intent intent) {

        }

        /**
         * 注册 Wifi 状态监听广播
         */
        private void registerWifiReceiver() {
                if (mWifiReceiver == null) {
                        mWifiReceiver = new WifiReceiver();
                        IntentFilter filter = new IntentFilter();
                        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
                        filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
                        registerReceiver(mWifiReceiver, filter);
                }
        }

        /**
         * 取消 wifi 广播监听
         */
        private void unRegisterWifiReceiver() {
                if (mWifiReceiver != null) {
                        unregisterReceiver(mWifiReceiver);
                        mWifiReceiver = null;
                }
        }

        private class WifiReceiver extends BroadcastReceiver {

                //记录网络断开的状态
                private boolean isDisConnected = false;

                //记录正在连接的状态
                private boolean isConnecting = false;

                @Override
                public void onReceive(Context context, Intent intent) {
                        WifiManager mWifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                        WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
                        if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {// wifi连接上与否
                                NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                                Logger.d(TAG, "网络已经改变----------> " + info.getState());
                                if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) {
                                        if (!isDisConnected) {
                                                Logger.e(TAG, "wifi已经断开");
                                                isDisConnected = true;
                                        }
                                }
                                else if (info.getState().equals(NetworkInfo.State.CONNECTING)) {
                                        if (!isConnecting) {
                                                Logger.e(TAG, "正在连接：" + wifiInfo.getSSID());
                                                isConnecting = true;
                                        }
                                }
                                else if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
                                        // 解决重复广播
                                        if (isConnecting) {
                                                isConnecting = false;
                                                isDisConnected = false;
                                                Logger.e(TAG, "连接到网络：" + wifiInfo.getSSID());

                                                if (WifiUtils.isU05Wifi(wifiInfo.getSSID())) {
                                                        mHandler.sendEmptyMessage(CONNECTED_U05);
                                                }
                                                else {
                                                        mWifiUtils.forgetNet(wifiInfo.getSSID());
                                                }
                                        }
                                }
                        }
                        else if (intent.getAction().equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)) {
                                int error = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, 0);
                                switch (error) {
                                        case WifiManager.ERROR_AUTHENTICATING:
                                                mWifiManager.removeNetwork(wifiInfo.getNetworkId());
                                                Logger.e(TAG, wifiInfo.getSSID() + "密码错误");
                                                break;
                                        default:
                                                break;
                                }
                        }
                }

        }

}
